// pages/userInfo/message/chatmessage.js
const app = getApp()
import api from '../../../config/api'
import path from '../../../config/path'
import webSocketManager from '../../../utils/websocket'
const { $Toast } = require('../../../dist/base/index');
const bubbleMixin = require('../../../utils/page-mixin');

Page({
  ...bubbleMixin,
  data: {
    targetUser: {},
    currentUser: {},
    messageGroups: [],
    inputMessage: '',
    loadingMore: false,
    hasMore: true,
    pageNo: 1,
    pageSize: 20,
    lastMsgId: '',
    autoFocus: false,
    currentLength: 0,
    initialLoadComplete: false,
    isActiveChat: false // 标记当前是否为活跃聊天
  },

  onLoad(options) {
    const { userId, userName, avatar } = options
    const currentUser = wx.getStorageSync('userInfo') || {}
    
    this.setData({
      targetUser: {
        userId: userId,
        userName: userName,
        avatar: avatar
      },
      currentUser: currentUser,
      isActiveChat: true
    })
    
    wx.setNavigationBarTitle({
      title: userName || '聊天'
    })
    
    const wsStatus = webSocketManager.getConnectionStatus()
    console.log('WebSocket连接状态:', wsStatus)
    
    if (!wsStatus.websocket || !wsStatus.stomp) {
      console.warn('WebSocket未连接，尝试重新连接...')
    }
    
    this.loadUnreadMessages()
    
    // 监听WebSocket消息
    webSocketManager.addMessageHandler(this.handleWebSocketMessage.bind(this))
    
    // 注册全局处理器，避免重复通知
    webSocketManager.addGlobalHandler(this.handleGlobalMessageForChat.bind(this))
  },

  onShow() {
    // 页面显示时标记为活跃聊天
    this.setData({ isActiveChat: true })
  },

  onHide() {
    // 页面隐藏时取消活跃标记
    this.setData({ isActiveChat: false })
  },

  onUnload() {
    webSocketManager.removeMessageHandler(this.handleWebSocketMessage)
    webSocketManager.removeGlobalHandler(this.handleGlobalMessageForChat)
    this.clearChatUser()
    this.setData({ isActiveChat: false })
  },

  clearChatUser() {
    api.post('message', path.path.clearChatUser, {});
  },

  // 处理全局消息（避免重复通知）
  handleGlobalMessageForChat(message) {
    if ((message.type === 'CHAT' || message.type === 'CHAT_NOTIFICATION') && 
        message.fromUserId === this.data.targetUser.userId &&
        this.data.isActiveChat) {
      console.log('在活跃聊天页面收到当前聊天对象的消息，跳过全局通知')
      return true // 返回true表示已处理，不需要再全局通知
    }
    return false
  },

  loadUnreadMessages() {
    const userId = this.data.targetUser.userId
    console.log('调用setChatUser接口，userId:', userId)
    
    const url = `${path.path.setChatUser}`
    
    api.post('message', url, {userId: userId})
      .then(res => {
        const unreadMessages = res.data || []
        console.log('未读消息:', unreadMessages)
        
        if (unreadMessages.length > 0) {
          this.processNewMessages(unreadMessages)
        } else {
          this.setData({
            messageGroups: [],
            initialLoadComplete: true
          })
        }
        
        this.setData({
          initialLoadComplete: true
        })
      })
      .catch(err => {
        console.error('获取未读消息失败:', err)
        this.setData({
          initialLoadComplete: true
        })
      })
  },

  loadMoreHistory() {
    if (this.data.loadingMore || !this.data.hasMore) {
      return
    }
    
    this.setData({ loadingMore: true })
    
    const params = {
      userId: parseInt(this.data.targetUser.userId),
      length: this.data.currentLength,
      pageSize: this.data.pageSize
    }
    
    console.log('加载更多历史消息参数:', params)
    
    api.get('message', path.path.getChatMessages, params).then(res => {
      const messages = res.data || []
      console.log('获取到历史消息:', messages)
      
      if (messages.length > 0) {
        const reversedMessages = [...messages].reverse()
        const newMessageGroups = this.groupMessagesByDate(reversedMessages)
        
        this.setData({
          messageGroups: [...newMessageGroups, ...this.data.messageGroups],
          currentLength: this.data.currentLength + messages.length,
          hasMore: messages.length === this.data.pageSize,
          pageNo: this.data.pageNo + 1
        })
      } else {
        this.setData({
          hasMore: false
        })
      }
    }).catch(err => {
      console.error('加载历史消息失败:', err)
      $Toast({
        content: '加载历史消息失败',
        icon: 'warning_fill'
      })
    }).finally(() => {
      this.setData({ loadingMore: false })
    })
  },

  safeDateParse(dateStr) {
    if (!dateStr) return new Date();
    
    let normalizedDateStr = dateStr;
    
    if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(dateStr)) {
      normalizedDateStr = dateStr.replace(/-/g, '/');
    }
    
    const date = new Date(normalizedDateStr);
    
    if (isNaN(date.getTime())) {
      console.warn('无效的日期格式:', dateStr, '使用当前时间替代');
      return new Date();
    }
    
    return date;
  },

  formatDate(dateStr) {
    if (!dateStr) return ''
    const date = this.safeDateParse(dateStr)
    const y = date.getFullYear()
    const m = `${date.getMonth() + 1}`.padStart(2, '0')
    const d = `${date.getDate()}`.padStart(2, '0')
    return `${y}-${m}-${d}`
  },

  formatTime(timeStr) {
    if (!timeStr) return ''
    const date = this.safeDateParse(timeStr)
    const hh = `${date.getHours()}`.padStart(2, '0')
    const mm = `${date.getMinutes()}`.padStart(2, '0')
    return `${hh}:${mm}`
  },

  processNewMessages(messages) {
    if (!messages || messages.length === 0) return
    
    const formattedMessages = messages.map(msg => ({
      id: msg.id || `${msg.created}-${Math.random()}`,
      content: msg.message || msg.content || '',
      time: this.formatTime(msg.created),
      direction: msg.postUserId === this.data.currentUser.id ? 'out' : 'in',
      created: msg.created
    }))
    
    this.addMessagesToLocal(formattedMessages)
    
    this.setData({
      currentLength: this.data.currentLength + formattedMessages.length
    })
  },

  groupMessagesByDate(messages) {
    const groups = {}
    
    messages.forEach(msg => {
      const date = this.formatDate(msg.created)
      if (!groups[date]) {
        groups[date] = []
      }
      
      groups[date].push({
        id: msg.id || `${msg.created}-${Math.random()}`,
        content: msg.message || msg.content || '',
        time: this.formatTime(msg.created),
        direction: msg.postUserId === this.data.currentUser.id ? 'out' : 'in',
        created: msg.created
      })
    })
    
    return Object.keys(groups).map(date => ({
      date: date,
      messages: groups[date]
    })).sort((a, b) => new Date(a.messages[0].created) - new Date(b.messages[0].created))
  },

  onInputMessage(e) {
    this.setData({
      inputMessage: e.detail.value
    })
  },

  sendMessage() {
    console.log('=== 开始发送消息流程 ===')
    
    const message = this.data.inputMessage.trim()
    if (!message) {
      console.log('消息为空，不发送')
      return
    }
    
    const messageData = {
      content: message,
      toUserId: this.data.targetUser.userId,
      picture: ''
    }
    
    console.log('准备发送的消息数据:', messageData)
    console.log('WebSocket连接状态:', webSocketManager.getConnectionStatus())
    
    const tempMessage = {
      id: `temp-${Date.now()}`,
      content: message,
      time: this.formatTime(new Date()),
      direction: 'out',
      created: new Date().toISOString(),
      status: 'sending'
    }
    
    console.log('添加临时消息到本地:', tempMessage)
    this.addMessageToLocal(tempMessage)
    
    this.setData({
      inputMessage: ''
    })
    
    try {
      console.log('开始通过WebSocket发送消息...')
      webSocketManager.send('/app/chat/send', messageData)
      console.log('WebSocket.send() 调用完成')
      
      setTimeout(() => {
        console.log('更新消息状态为sent')
        this.updateMessageStatus(tempMessage.id, 'sent')
      }, 1000)
      
    } catch (error) {
      console.error('发送消息失败:', error)
      this.updateMessageStatus(tempMessage.id, 'failed')
      $Toast({
        content: '发送失败，请检查网络连接',
        icon: 'warning_fill'
      })
    }
  },

  addMessageToLocal(message) {
    this.addMessagesToLocal([message])
  },

  addMessagesToLocal(messages) {
    if (!messages || messages.length === 0) return
    
    let newMessageGroups = [...this.data.messageGroups]
    
    messages.forEach(message => {
      const date = this.formatDate(message.created)
      let foundGroup = false
      
      newMessageGroups = newMessageGroups.map(group => {
        if (group.date === date) {
          foundGroup = true
          const exists = group.messages.some(msg => msg.id === message.id)
          if (!exists) {
            return {
              ...group,
              messages: [...group.messages, message]
            }
          }
        }
        return group
      })
      
      if (!foundGroup) {
        newMessageGroups.push({
          date: date,
          messages: [message]
        })
      }
    })
    
    newMessageGroups.sort((a, b) => new Date(a.messages[0].created) - new Date(b.messages[0].created))
    
    this.setData({
      messageGroups: newMessageGroups,
      lastMsgId: messages[messages.length - 1].id
    })
    
    setTimeout(() => {
      this.scrollToBottom()
    }, 100)
  },

  updateMessageStatus(messageId, status) {
    const newMessageGroups = this.data.messageGroups.map(group => {
      const newMessages = group.messages.map(msg => {
        if (msg.id === messageId) {
          return { ...msg, status: status }
        }
        return msg
      })
      return { ...group, messages: newMessages }
    })
    
    this.setData({
      messageGroups: newMessageGroups
    })
  },

  handleWebSocketMessage(message) {
    console.log('收到WebSocket消息:', message)
    
    if (message.type === 'CHAT') {
      const fromUserId = message.fromUserId?.toString()
      const toUserId = message.toUserId?.toString()
      const currentUserId = this.data.currentUser.id?.toString()
      const targetUserId = this.data.targetUser.userId?.toString()
      
      console.log('消息用户匹配检查:', {
        fromUserId, toUserId, currentUserId, targetUserId
      })
      
      if ((fromUserId === targetUserId && toUserId === currentUserId) ||
          (fromUserId === currentUserId && toUserId === targetUserId)) {
        
        console.log('匹配成功，添加到聊天界面')
        this.addMessageToLocal({
          id: message.id || `msg-${Date.now()}`,
          content: message.content,
          time: this.formatTime(new Date()),
          direction: fromUserId === currentUserId ? 'out' : 'in',
          created: new Date().toISOString()
        })
      }
    }
  },

  scrollToBottom() {
    setTimeout(() => {
      wx.pageScrollTo({
        scrollTop: 99999,
        duration: 300
      })
    }, 100)
  }
})